package com.xhui.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhui.reggie.common.CustomException;
import com.xhui.reggie.entity.Category;
import com.xhui.reggie.entity.Dish;
import com.xhui.reggie.entity.Setmeal;
import com.xhui.reggie.mapper.CategoryMapper;
import com.xhui.reggie.service.CategoryService;
import com.xhui.reggie.service.DishService;
import com.xhui.reggie.service.SetmealService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private DishService dishService; // 操作菜品

    @Resource
    private SetmealService setmealService; // 操作套餐


    /**
     * 根据id进行删除分类，由于数据库表均无外键关联，须在代码层次判断
     * @param categoryId 菜品/套餐id
     */
    @Override
    public void remove(Long categoryId) {
        // 查询当前分类是否关联了菜品，若关联，抛出异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, categoryId);
        int dishCount = dishService.count(dishLambdaQueryWrapper);

        //查询当前分类是否关联了菜品，若关联，抛出异常
        if (dishCount > 0){
        // 分类id已被菜品关联,抛出异常
            throw new CustomException("当前分类下关联了菜品，不能删除！");
        }
        // 查询当前分类是否关联套餐，若关联，抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, categoryId);
        int setmealCount = setmealService.count(setmealLambdaQueryWrapper);

        //查询当前分类是否关联了套餐，若关联，抛出异常
        if (setmealCount > 0) {
            // 分类id已被套餐关联,抛出异常
            throw new CustomException("当前分类下已关联了套餐，不能删除！");
        }

        // categoryId无任何关联，可进行正常删除
        super.removeById(categoryId);
    }

}
